package com.example.select_lesson;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.balysv.materialmenu.MaterialMenuDrawable;

import java.util.ArrayList;
import java.util.List;


public class SearchClassActivity extends ActionBarActivity implements AdapterView.OnItemLongClickListener{

    /**
     * 跳转
     * @param context 传递过来的上下文
     * @param studentId 传递过来的学生id
     */
    public static void actionStart(Context context, String studentId) {
        Intent intent = new Intent(context, SearchClassActivity.class);
        intent.putExtra("student_id", studentId);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }

    private String studentId;
    private MaterialMenuDrawable materialMenu;
    private BounceListView mListView;
    private SelectedClassInformationAdapter adapter;
    private SQLiteDatabase db;
    private MyDataBaseHelper dbHelper;
    /**
     * 存放课程Id的list
     */
    private ArrayList<Integer> classIdList = new ArrayList<Integer>();
    /**
     * 存放课程名字的list
     */
    private ArrayList<String> lessonNameList = new ArrayList<String>();
    /**
     * 存放课程已选选择人数的list
     */
    private ArrayList<Integer> selectedStudentNumberList = new ArrayList<Integer>();
    /**
     * 存放课程最多选择人数的list
     */
    private ArrayList<Integer> studentNumberList = new ArrayList<Integer>();
    /**
     * 存放课程时间的list
     */
    private ArrayList<String> lessonTimeList = new ArrayList<String>();
    /**
     * 存放教师Id的list
     */
    private ArrayList<Integer> teacherIdList = new ArrayList<Integer>();
    /**
     * 存放教师名字的list
     */
    private ArrayList<String> teacherNameList = new ArrayList<String>();
    /**
     * 存放所有要显示在listView上的信息的list
     */
    private ArrayList<SelectedClassInformation> SelectedClassInformationList = new ArrayList<SelectedClassInformation>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.my_dark_blue));
        }

/*        *//**
         * 测试数据
         *//*
        dbHelper = new MyDataBaseHelper(this, "StudentManager.db", null, 1);
        db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("studentId", 1);
        values.put("classId", 2);
        db.insert("SELECT_LESSON", null, values);
        values.clear();
        values = new ContentValues();
        values.put("studentId", 1);
        values.put("classId", 3);
        db.insert("SELECT_LESSON", null, values);
        values.clear();
        db.close();*/


        // 得到传递过来的studentId
        studentId = getIntent().getStringExtra("student_id");
        // 初始化数据库
        initDb();
        // 初始化给listView的数据
        initSelectedClassInformationList();

        initView();
        setToolbar();
    }

    private void initView() {
        mListView = (BounceListView) findViewById(R.id.list_view);
        adapter = new SelectedClassInformationAdapter(SearchClassActivity.this, R.layout.item_search_class, SelectedClassInformationList);
        mListView.setAdapter(adapter);
        mListView.setOnItemLongClickListener(this);
    }

    /**
     * 数据库操作
     */
    private void initDb() {
        dbHelper = new MyDataBaseHelper(this, "StudentManager.db", null, 1);
        dbHelper.getWritableDatabase();
        db = dbHelper.getWritableDatabase();
        /**
         *            ----------------------------------
         *            |   获得该学生所有的classId        |
         *            ----------------------------------
         * 通过传过来的studentId，在中间表中寻找和这个studentId绑定的所有classId
         * 并把它们存放在classIdList中
         */
        Cursor cursor = db.rawQuery("select * from SELECT_LESSON where studentId=?",
                new String[] {studentId});
        if (cursor.moveToFirst()) {
            do {
                classIdList.add(cursor.getInt(cursor.getColumnIndex("classId")));
            } while (cursor.moveToNext());
        }
        cursor.close();
        /**
         *            ----------------------------------
         *            | 通过classId，获得所有class信息   |
         *            ----------------------------------
         *  通过classIdList中每个classId
         *  循环把每个classId所指向的lesson中数据取出
         */
        for (int i = 0; i < classIdList.size(); ++i) {
            cursor = db.rawQuery("select * from LESSON where lessonId=?",
                    new String[] {classIdList.get(i) + ""});
            if (cursor.moveToFirst()) {
                do {
                    lessonNameList.add(cursor.getString(cursor.getColumnIndex("lessonName")));
                    studentNumberList.add(cursor.getInt(cursor.getColumnIndex("studentNumber")));
                    lessonTimeList.add(cursor.getString(cursor.getColumnIndex("lessonTime")));
                    teacherIdList.add(cursor.getInt(cursor.getColumnIndex("teacherId")));
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        /**
         *            ----------------------------------
         *            | 通过classId，获得已选课人数      |
         *            ----------------------------------
         * 通过classId在中间表中寻找已经选择该课程的人数
         * 并添加到selectedStudentNumberList中
         */
        for (int i = 0; i < classIdList.size(); ++i) {
            cursor = db.rawQuery("select * from SELECT_LESSON where classId=?",
                    new String[] {classIdList.get(i) + ""});
            int studentNumber = 0;
            if (cursor.moveToFirst()) {
                do {
                    studentNumber++;
                } while (cursor.moveToNext());
            }
            selectedStudentNumberList.add(studentNumber);
            cursor.close();
        }
        /**
         *            ----------------------------------
         *            | 通过teacherId，获得对应老师名字   |
         *            ----------------------------------
         * 通过teacherId，获得对应老师名字
         * 并添加到teacherNameList中
         */
        for (int i = 0; i < teacherIdList.size(); ++i) {
            Log.d("teacherName",teacherIdList.get(i)+"");
            cursor = db.rawQuery("select * from TEACHER where teacherId=?",
                    new String[] {teacherIdList.get(i) + ""});
            if (cursor.moveToFirst()) {
                do {
                    Log.d("teacherName", "aaa");
                    teacherNameList.add(cursor.getString(cursor.getColumnIndex("teacherName")));
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
    }

    /**
     * 初始化给listView的数据
     */
    private void initSelectedClassInformationList() {
        for (int i = 0; i < classIdList.size(); ++i) {
            SelectedClassInformation selectedClassInformation =
                    new SelectedClassInformation(lessonNameList.get(i),
                            studentNumberList.get(i),
                            selectedStudentNumberList.get(i),
                            lessonTimeList.get(i),
                            teacherNameList.get(i)
                            );
            SelectedClassInformationList.add(selectedClassInformation);
        }
    }


    private void setToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("  已选课程");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                switch (materialMenu.getIconState()) {
                    case BURGER:
                        break;
                    case ARROW:
                        materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW, false);
                        HomeActivity.actionStart(getApplicationContext(), studentId);
                        finish();
                        break;
                    case X:
                        break;
                    case CHECK:
                        break;
                }

            }
        });
        materialMenu = new MaterialMenuDrawable(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN);
        materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW, false);
        toolbar.setNavigationIcon(materialMenu);
        materialMenu.setNeverDrawTouch(true);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search_class, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("删除");
        builder.setMessage("是否删除");
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                db = dbHelper.getWritableDatabase();
                db.delete("SELECT_LESSON", "classId=? and studentId=?", new String[] {classIdList.get(position) + "", studentId});
                SelectedClassInformationList.remove(position);
                classIdList.remove(position);
                adapter.notifyDataSetChanged();
                dialog.cancel();
            }
        });
        builder.show();
        return true;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            HomeActivity.actionStart(getApplicationContext(), studentId);
            finish();
        }
        return true;
    }
}

/**
 * 新建一个已选课程信息类
 * 便于之后给listView传递数据
 */
class SelectedClassInformation {
    private String lessonName;
    private int studentNumber;
    private int selectedStudentNumber;
    private String lessonTime;
    private String teacherName;

    SelectedClassInformation(String lessonName, int studentNumber, int selectedStudentNumber,
                             String lessonTime, String teacherName) {
        this.lessonName = lessonName;
        this.studentNumber = studentNumber;
        this.selectedStudentNumber = selectedStudentNumber;
        this.lessonTime = lessonTime;
        this.teacherName = teacherName;
    }
    public String getLessonName() {
        return lessonName;
    }

    public void setLessonName(String lessonName) {
        this.lessonName = lessonName;
    }

    public int getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(int studentNumber) {
        this.studentNumber = studentNumber;
    }

    public int getSelectedStudentNumber() {
        return selectedStudentNumber;
    }

    public void setSelectedStudentNumber(int selectedStudentNumber) {
        this.selectedStudentNumber = selectedStudentNumber;
    }

    public String getLessonTime() {
        return lessonTime;
    }

    public void setLessonTime(String lessonTime) {
        this.lessonTime = lessonTime;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }
}

class SelectedClassInformationAdapter extends ArrayAdapter<SelectedClassInformation> {

    private int resouceId;


    public SelectedClassInformationAdapter(Context context, int resource, List<SelectedClassInformation> objects) {
        super(context, resource, objects);
        resouceId = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        SelectedClassInformation selectedClassInformation = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resouceId, null);
            viewHolder = new ViewHolder();
            viewHolder.textView = (TextView) view.findViewById(R.id.tv_item);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.textView.setText("课程名：" + selectedClassInformation.getLessonName()
                                    + "\n课程时间：" + selectedClassInformation.getLessonTime()
                                    + "\n已选人数/总人数：" + selectedClassInformation.getSelectedStudentNumber()
                                    + "/" + selectedClassInformation.getStudentNumber()
                                    + "\n教师：" + selectedClassInformation.getTeacherName());
        return view;
    }

    private class ViewHolder {
        TextView textView;
    }
}